<?php

namespace App\Common\Validate;

use App\Common\Util\TP;
use think\Validate;

/**
 * Class AbstractValidate
 */
abstract class AbstractValidate extends Validate
{
    protected $failException = true;

    protected array $data = [];

    public function __construct(bool $isAutoValidate = true)
    {
        $this->data = TP::request()->post();

        $this->rule($this->allRules());
        $this->message($this->allMessages());

        parent::__construct();

        if ($isAutoValidate) {
            $this->scene($this->autoGetScene())->check($this->data);
        }
    }

    protected function autoGetScene(): string
    {
        $ruleName = TP::route()->getCurrentRule()->getName();

        return explode('@', $ruleName)[1];
    }

    /**
     * 获取所有数据
     *
     * @return array
     */
    public function data(): array
    {
        return $this->data;
    }

    /**
     * @param string $key
     * @param string|null $default
     * @return array|mixed
     */
    public function input(string $key = '', string $default = null): mixed
    {
        return TP::request()->param($key, $default);
    }

    public function post(string $key = '', string $default = null): mixed
    {
        return TP::request()->post($key, $default);
    }

    public function get(string $key = '', string $default = null): mixed
    {
        return TP::request()->get($key, $default);
    }

    /**
     * 获取验证的字段数据
     *
     * @return array
     */
    public function validate(): array
    {
        $ruleField = array_keys($this->rule);

        return array_filter($this->data, fn($k) => in_array($k, $ruleField), ARRAY_FILTER_USE_KEY);
    }

    abstract protected function allRules(): array;

    abstract protected function allMessages(): array;
}